package com.tanhua.sso.service;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.tanhua.sso.config.AliyunSMSConfig;
import com.tanhua.sso.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

@Slf4j
@Service
public class SmsService {

    @Autowired
    private AliyunSMSConfig aliyunSMSConfig;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 发送短信服务
     * @param mobile
     * @return
     */
    public String sendSms(String mobile){
        //设置RegionId、AK和SK
        DefaultProfile profile = DefaultProfile.getProfile(aliyunSMSConfig.getRegionId(),
                aliyunSMSConfig.getAccessKeyId(), aliyunSMSConfig.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);

        //生成随机码
        String code = RandomUtils.nextInt(100000,999999)+"";

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(aliyunSMSConfig.getDomain());
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", aliyunSMSConfig.getRegionId());
        request.putQueryParameter("PhoneNumbers", mobile); //目标手机号
        request.putQueryParameter("SignName", aliyunSMSConfig.getSignName()); //签名名称
        request.putQueryParameter("TemplateCode", aliyunSMSConfig.getTemplateCode()); //短信模板code
        request.putQueryParameter("TemplateParam", "{\"code\":\""+code+"\"}");//模板中变量替换

        try {
            CommonResponse response = client.getCommonResponse(request);
            //获得sms短信服务发送的响应信息
            //{"Message":"OK","RequestId":"EC2D4C9A-0EAC-4213-BE45-CE6176E1DF23","BizId":"110903802851113360^0","Code":"OK"}
            String data = response.getData();
            //如果返回的消息中包含  "Message":"OK"  ，表示短信发送成功
            //contains(CharSequence seq, CharSequence searchSeq)  ->  判断seq这个字符序列是否包含searchSeq这个字符序列
            if (StringUtils.contains(data,"\"Message\":\"OK\"")){
                //返回随机码
                return code;
            }
            //这里的失败返回sms服务的响应消息
            log.error("发送短信失败："+data);
        } catch (Exception e) {
            //这里的失败是异常失败，返回手机号和异常信息
            log.error("发送短信失败："+mobile,e);
        }

        //失败返回null，交给controller判断
        return null;
    }

    /**
     * 发送验证码,验证手机号是否存在redis中
     * @param phone
     * @return
     */
    public ErrorResult sendCheckCode(String phone){
        //redisKey -> 存入redis中的key
        String redisKey = "CHECK_CODE_" + phone;

        //先判断该手机号发送的验证码是否还未失效
        //hasKey() -> 判断这个key在redis中是否存在，存在true，不存在false
        if (redisTemplate.hasKey(redisKey)){
            String msg = "发送短信验证码失败！";
            //封装和前端约定好的信息对象并返回
            return ErrorResult.builder().errCode("000000").errMessage(msg).build();
        }

        //不存在redis中，调用发送短信服务，返回code结果
        //String code = this.sendSms(phone);
        String code = "123456";

        //判断调用发送短信服务是否成功
        //code = null -> 发送失败
        //code != null -> 发送成功
        if(StringUtils.isEmpty(code)){
            String msg = "发送短信验证码失败！";
            return ErrorResult.builder().errCode("000000").errMessage(msg).build();
        }

        //短信发送成功，将验证码保存到redis中，有效期为5分钟
        this.redisTemplate.opsForValue().set(redisKey, code, Duration.ofMinutes(5));

        //成功返回null
        return null;
    }
}
